import { useMemoizedFn } from 'ahooks'
import { useMemo } from 'react'
import { IPC_CHANNELS } from 'shared/ipcChannels'
import { create } from 'zustand'
import { createJSONStorage, persist } from 'zustand/middleware'
import { immer } from 'zustand/middleware/immer'
import { EVENTS, eventEmitter } from '@/utils/events'
import { mergeWithoutArray } from '@/utils/misc'
import { useAccounts } from './useAccounts'
import { type Message, useAutoReply } from './useAutoReply'

type ListeningStatus = 'waiting' | 'listening' | 'stopped' | 'error'

// 导出播放队列相关类型（从playbackQueue工具导入）
export type { PlaybackQueueItem, RecycleItem, PlaybackContentType, PlayMode } from '@/utils/playbackQueue'

// 为了向后兼容，保留原有的类型别名
export type PreviewQueueItem = import('@/utils/playbackQueue').PlaybackQueueItem
export type RecycleBinItem = import('@/utils/playbackQueue').RecycleItem

interface AIAssistContext {
  isBroadcasting: boolean
  isListening: ListeningStatus
  config: AIAssistConfig
  broadcastedComments: string[] // 已经播报过的评论ID
  contentRewrite: {
    isPlaying: boolean // 是否正在播放
    currentIndex: number // 当前播放索引
    previewQueue: PreviewQueueItem[] // 播放预览队列
    recycleBin: RecycleBinItem[] // 回收站
    currentSequentialIndex: number // 顺序播放索引
    currentPlayingId: string | null // 当前正在播放的ID
  }
}

interface AIAssistState {
  contexts: Record<string, AIAssistContext>
}

interface AIAssistAction {
  setIsBroadcasting: (accountId: string, isBroadcasting: boolean) => void
  setIsListening: (accountId: string, isListening: ListeningStatus) => void
  updateConfig: (accountId: string, config: Partial<AIAssistConfig>) => void
  addBroadcastedComment: (accountId: string, commentId: string) => void
  setContentRewritePlaying: (accountId: string, isPlaying: boolean) => void
  setContentRewriteIndex: (accountId: string, index: number) => void
  setPreviewQueue: (accountId: string, queue: PreviewQueueItem[]) => void
  setRecycleBin: (accountId: string, bin: RecycleBinItem[]) => void
  setCurrentSequentialIndex: (accountId: string, index: number) => void
  setCurrentPlayingId: (accountId: string, id: string | null) => void
}

const createDefaultConfig = (): AIAssistConfig => ({
  provider: 'aliyun', // 默认使用阿里云
  aliyun: {
    accessKeyId: '',
    accessKeySecret: '',
    appKey: '',
    endpoint: 'https://nls-gateway.aliyuncs.com/stream/v1/tts',
  },
  tencent: {
    secretId: '', // SecretId
    secretKey: '', // SecretKey
    region: 'ap-guangzhou', // 地域，默认广州
  },
  edge: {
    voice: 'zh-CN-XiaoxiaoNeural', // 默认使用晓晓音色
    apiUrl: 'http://localhost:5000', // 本地服务地址
  },
  voice: {
    type: 'preset',
    presetVoiceId: '1001', // 默认音色（智瑜）
    customVoices: [], // 自定义音色列表
    voiceRotation: {
      enable: false,
      interval: [5, 15], // 默认5-15分钟随机切换
      voiceIds: [],
    },
  },
  broadcast: {
    enable: true,
    speed: 1.0,
    volume: 50,
    pitch: 0,
  },
  playback: {
    interval: {
      min: 3, // 最小间隔3秒
      max: 10, // 最大间隔10秒
    },
    randomization: {
      enable: false,
      speedRange: [0.9, 1.1], // 语速随机范围
      volumeRange: [45, 55], // 音量随机范围
      pitchRange: [-50, 50], // 音调随机范围
    },
    recycle: {
      enable: false, // 默认关闭回收站重播
      probability: 20, // 默认20%的概率重播旧话术
    },
    timeAnnouncement: {
      enable: false,
      interval: {
        min: 5, // 最小间隔5分钟
        max: 15, // 最大间隔15分钟
      },
      templates: ['现在是{时间}', '当前时间{时间}'],
      mode: 'random',
    },
    userInteraction: {
      enable: false, // 默认关闭，需要手动开启
      interval: {
        min: 1, // 最小间隔1秒
        max: 5, // 最大间隔5秒
      },
      deduplication: {
        enable: true, // 默认启用防重复
        duration: 60, // 60秒内同一用户的相同类型互动不重复播报
      },
      templates: {
        room_enter: ['欢迎{用户}来到直播间', '{用户}欢迎你'],
        room_like: ['感谢{用户}的点赞', '{用户}点赞了'],
        room_follow: ['感谢{用户}的关注', '{用户}关注了直播间'],
        subscribe_merchant_brand_vip: ['欢迎{用户}加入品牌会员', '{用户}成为品牌会员'],
        live_order: ['{用户}购买了{商品}', '感谢{用户}购买{商品}'],
        ecom_fansclub_participate: ['欢迎{用户}加入粉丝团', '{用户}成为粉丝'],
      },
      mode: 'random',
      playMode: 'next', // ✅ 新增：播放模式，默认等待播放完成
    },
    welcomeUser: {
      enable: false,
      interval: {
        min: 1, // 最小间隔1分钟
        max: 5, // 最大间隔5分钟
      },
      templates: ['欢迎{用户}来到直播间', '感谢{用户}的关注'],
      mode: 'random',
    },
    pause: {
      enable: false,
      duration: [200, 500], // 停顿200-500毫秒
    },
  },
  commentFilter: {
    enableFilter: false,
    keywords: [],
  },
  smartReply: {
    enable: false,
    checkInterval: 5, // 默认5秒检测一次
    keywords: [],
    playMode: 'next', // 默认等待播放完成，避免打断
    deduplication: {
      userInterval: 120, // 默认120秒内不重复回复同一用户
      questionInterval: 3600, // 默认1小时内不重复回复同一用户的同一问题
    },
  },
  contentRewrite: {
    enable: false,
    scripts: [],
    playback: {
      mode: 'manual',
      interval: [30, 60], // 默认30-60秒
      randomOrder: false,
    },
  },
})

const createDefaultContext = (): AIAssistContext => ({
  isBroadcasting: false,
  isListening: 'stopped',
  config: createDefaultConfig(),
  broadcastedComments: [],
  contentRewrite: {
    isPlaying: false,
    currentIndex: 0,
    previewQueue: [],
    recycleBin: [],
    currentSequentialIndex: 0,
    currentPlayingId: null,
  },
})

export const useAIAssistStore = create<AIAssistState & AIAssistAction>()(
  persist(
    immer(set => {
      eventEmitter.on(EVENTS.ACCOUNT_REMOVED, (accountId: string) => {
        set(state => {
          delete state.contexts[accountId]
        })
      })

      const ensureContext = (state: AIAssistState, accountId: string) => {
        if (!state.contexts[accountId]) {
          state.contexts[accountId] = createDefaultContext()
        }
        return state.contexts[accountId]
      }

      return {
        contexts: {},
        setIsBroadcasting: (accountId, isBroadcasting) =>
          set(state => {
            const context = ensureContext(state, accountId)
            context.isBroadcasting = isBroadcasting
          }),
        setIsListening: (accountId, isListening) =>
          set(state => {
            const context = ensureContext(state, accountId)
            context.isListening = isListening
          }),
        updateConfig: (accountId, configUpdates) =>
          set(state => {
            const context = ensureContext(state, accountId)
            const newConfig = mergeWithoutArray(context.config, configUpdates)
            context.config = newConfig
          }),
        addBroadcastedComment: (accountId, commentId) =>
          set(state => {
            const context = ensureContext(state, accountId)
            // 只保留最近 500 条记录
            context.broadcastedComments = [
              commentId,
              ...context.broadcastedComments,
            ].slice(0, 500)
          }),
        setContentRewritePlaying: (accountId, isPlaying) =>
          set(state => {
            const context = ensureContext(state, accountId)
            context.contentRewrite.isPlaying = isPlaying
          }),
        setContentRewriteIndex: (accountId, index) =>
          set(state => {
            const context = ensureContext(state, accountId)
            context.contentRewrite.currentIndex = index
          }),
        setPreviewQueue: (accountId, queue) =>
          set(state => {
            const context = ensureContext(state, accountId)
            context.contentRewrite.previewQueue = queue
          }),
        setRecycleBin: (accountId, bin) =>
          set(state => {
            const context = ensureContext(state, accountId)
            context.contentRewrite.recycleBin = bin
          }),
        setCurrentSequentialIndex: (accountId, index) =>
          set(state => {
            const context = ensureContext(state, accountId)
            context.contentRewrite.currentSequentialIndex = index
          }),
        setCurrentPlayingId: (accountId, id) =>
          set(state => {
            const context = ensureContext(state, accountId)
            context.contentRewrite.currentPlayingId = id
          }),
      }
    }),
    {
      name: 'ai-assist',
      version: 1,
      storage: createJSONStorage(() => localStorage),
      partialize: state => ({
        contexts: Object.fromEntries(
          Object.entries(state.contexts).map(([accountId, context]) => [
            accountId,
            {
              config: context.config,
            },
          ]),
        ),
      }),
      merge: (persistedState, currentState) => {
        const mergedContexts: Record<string, AIAssistContext> = {}
        const persistedContexts =
          (persistedState as Partial<AIAssistState>)?.contexts || {}

        const allAccountIds = new Set([
          ...Object.keys(currentState.contexts),
          ...Object.keys(persistedContexts),
        ])

        for (const accountId of allAccountIds) {
          const currentContextPartial = currentState.contexts[accountId] || {}
          const persistedContextPartial = persistedContexts[accountId] as
            | Partial<AIAssistContext>
            | undefined

          mergedContexts[accountId] = {
            ...createDefaultContext(),
            ...currentContextPartial,
            ...(persistedContextPartial && {
              config: persistedContextPartial.config,
            }),
          }
        }

        return {
          ...currentState,
          contexts: mergedContexts,
        }
      },
    },
  ),
)

export function useAIAssist() {
  const store = useAIAssistStore()
  const { currentAccountId } = useAccounts()
  const { comments, isListening, setIsListening } = useAutoReply()

  const context = useMemo(() => {
    return store.contexts[currentAccountId] || createDefaultContext()
  }, [store.contexts, currentAccountId])

  const { isBroadcasting, config, broadcastedComments, contentRewrite } = context

  // 处理评论播报
  const handleCommentBroadcast = useMemoizedFn(
    async (comment: Message, accountId: string) => {
      const currentContext =
        useAIAssistStore.getState().contexts[accountId] ||
        createDefaultContext()
      const { isBroadcasting, config, broadcastedComments } = currentContext
      
      // 如果未启用或已播报过，跳过
      if (
        !isBroadcasting ||
        !config.broadcast.enable ||
        broadcastedComments.includes(comment.msg_id)
      ) {
        return
      }

      let text = ''
      const userName = comment.nick_name

      // 根据消息类型生成播报文本
      if (comment.msg_type === 'comment') {
        // 评论类型：检查关键词过滤
        if (config.commentFilter.enableFilter) {
          const hasKeyword = config.commentFilter.keywords.some(keyword =>
            comment.content?.includes(keyword),
          )
          if (!hasKeyword) {
            return
          }
        }
        text = `${userName}说：${comment.content}`
      } else {
        // 用户互动类型：检查是否启用
        const userInteraction = config.playback?.userInteraction
        
        console.log(`[用户互动播报] 收到${comment.msg_type}消息，用户:${userName}，开关:${userInteraction?.enable}`)
        
        if (!userInteraction?.enable) {
          console.log(`[用户互动播报] ❌ 未启用，跳过`)
          return
        }

        // 防重复播报检查
        if (userInteraction.deduplication?.enable) {
          const deduplicationKey = `${accountId}_${userName}_${comment.msg_type}`
          const lastBroadcastTime = (window as any).__userInteractionCache?.[deduplicationKey]
          const now = Date.now()
          const duration = (userInteraction.deduplication.duration || 60) * 1000

          if (lastBroadcastTime && (now - lastBroadcastTime) < duration) {
            // 在防重复时间窗口内，跳过
            return
          }

          // 记录本次播报时间
          if (!(window as any).__userInteractionCache) {
            (window as any).__userInteractionCache = {}
          }
          (window as any).__userInteractionCache[deduplicationKey] = now
        }

        // 根据不同的互动类型生成播报文本
        const templates = userInteraction.templates
        let templateList: string[] = []

        switch (comment.msg_type) {
          case 'room_enter':
            templateList = (templates?.room_enter || []).filter(t => t && t.trim())
            break
          case 'room_like':
            templateList = (templates?.room_like || []).filter(t => t && t.trim())
            break
          case 'room_follow':
            templateList = (templates?.room_follow || []).filter(t => t && t.trim())
            break
          case 'subscribe_merchant_brand_vip':
            templateList = (templates?.subscribe_merchant_brand_vip || []).filter(t => t && t.trim())
            break
          case 'live_order':
            templateList = (templates?.live_order || []).filter(t => t && t.trim())
            break
          case 'ecom_fansclub_participate':
            templateList = (templates?.ecom_fansclub_participate || []).filter(t => t && t.trim())
            break
          default:
            return // 不支持的消息类型
        }

        if (templateList.length === 0) {
          console.log(`[用户互动播报] ❌ ${comment.msg_type} 未配置模板`)
          return // 没有配置模板
        }

        // 选择模板（随机或顺序）
        const mode = userInteraction.mode || 'random'
        let template = ''
        if (mode === 'random') {
          template = templateList[Math.floor(Math.random() * templateList.length)]
        } else {
          // 顺序模式：使用全局索引
          const indexKey = `${accountId}_${comment.msg_type}_index`
          if (!(window as any).__userInteractionIndexes) {
            (window as any).__userInteractionIndexes = {}
          }
          const currentIndex = (window as any).__userInteractionIndexes[indexKey] || 0
          template = templateList[currentIndex % templateList.length]
          const nextIndex = currentIndex + 1
          ;(window as any).__userInteractionIndexes[indexKey] = nextIndex
        }

        // 替换占位符
        text = template
          .replace(/\{用户\}/g, userName)
          .replace(/\{昵称\}/g, userName)
        
        if (comment.msg_type === 'live_order') {
          text = text.replace(/\{商品\}/g, comment.product_title || '')
        }
        
        console.log(`[用户互动播报] ✅ 生成播报: ${text}`)
      }

      if (!text) {
        return
      }

      // ✅ 修复：将用户互动内容加入播放队列
      const interactionPlayMode = (config.playback?.userInteraction?.playMode || 'next') as 'immediate' | 'next'
      
      // 发送事件到ContentRewriteCard，让它将内容加入队列
      (window.ipcRenderer as any).send('ai-assist:add-to-queue', {
        accountId,
        type: 'user_interaction' as const,
        originalContent: `${userName} - ${comment.msg_type}`,
        rewrittenContent: text,
        playMode: interactionPlayMode,
      })
      
      console.log(`[用户互动播报] ✅ 已加入队列，播放模式: ${interactionPlayMode}`)
      
      // 标记为已播报
      store.addBroadcastedComment(accountId, comment.msg_id)
    },
  )

  return {
    // 状态
    isBroadcasting,
    isListening,
    config,
    comments,
    contentRewrite,

    // Actions
    setIsBroadcasting: (broadcasting: boolean) =>
      store.setIsBroadcasting(currentAccountId, broadcasting),
    setIsListening: (listening: ListeningStatus) => {
      setIsListening(listening)
      store.setIsListening(currentAccountId, listening)
    },
    updateConfig: (configUpdates: Partial<AIAssistConfig>) =>
      store.updateConfig(currentAccountId, configUpdates),
    handleCommentBroadcast,
    setContentRewritePlaying: (isPlaying: boolean) =>
      store.setContentRewritePlaying(currentAccountId, isPlaying),
    setContentRewriteIndex: (index: number) =>
      store.setContentRewriteIndex(currentAccountId, index),
    setPreviewQueue: (queue: PreviewQueueItem[]) =>
      store.setPreviewQueue(currentAccountId, queue),
    setRecycleBin: (bin: RecycleBinItem[]) =>
      store.setRecycleBin(currentAccountId, bin),
    setCurrentSequentialIndex: (index: number) =>
      store.setCurrentSequentialIndex(currentAccountId, index),
    setCurrentPlayingId: (id: string | null) =>
      store.setCurrentPlayingId(currentAccountId, id),

    // 测试语音配置
    testVoiceConfig: async () => {
      try {
        const provider = config.provider || 'aliyun'
        const providerName = 
          provider === 'aliyun' ? '阿里云 CosyVoice' : 
          provider === 'tencent' ? '腾讯云 TTS' : 
          'Edge-TTS'
        
        console.log('========== 测试语音配置 ==========')
        console.log('语音服务厂商:', providerName)
        
        if (provider === 'aliyun') {
          console.log('阿里云配置:', {
            accessKeyId: config.aliyun.accessKeyId?.substring(0, 10) + '...',
            accessKeySecret: config.aliyun.accessKeySecret?.substring(0, 10) + '...',
            appKey: config.aliyun.appKey?.substring(0, 10) + '...',
            endpoint: config.aliyun.endpoint,
          })
        } else if (provider === 'tencent') {
          console.log('腾讯云配置:', {
            secretId: config.tencent?.secretId?.substring(0, 10) + '...',
            secretKey: config.tencent?.secretKey?.substring(0, 10) + '...',
            region: config.tencent?.region || 'ap-guangzhou',
          })
        } else if (provider === 'edge') {
          console.log('Edge-TTS 配置:', {
            voice: config.edge?.voice || 'zh-CN-XiaoxiaoNeural（默认）',
          })
        }
        console.log('==================================')
        
        const result = await window.ipcRenderer.invoke(
          IPC_CHANNELS.tasks.aiAssist.testVoiceConfig,
          config,
        )
        return result
      } catch (err) {
        console.error('测试语音配置失败:', err)
        return { success: false, error: String(err) }
      }
    },

    // 获取预设音色列表
    getPresetVoices: async () => {
      try {
        const voices = await window.ipcRenderer.invoke(
          IPC_CHANNELS.tasks.aiAssist.getPresetVoices,
        )
        return voices
      } catch (err) {
        console.error('获取预设音色失败:', err)
        return []
      }
    },

    // 克隆声音
    cloneVoice: async (audioFile: string, voiceName: string) => {
      try {
        const result = await window.ipcRenderer.invoke(
          IPC_CHANNELS.tasks.aiAssist.cloneVoice,
          {
            audioFile,
            voiceName,
            config: { aliyun: config.aliyun },
          },
        )
        return result
      } catch (err) {
        console.error('克隆声音失败:', err)
        return { success: false, error: String(err) }
      }
    },
  }
}

